package ReflectSQL;

import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtils {

    public static <T> List<T> list(String sql, Class<T> byteClss) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException {

        ArrayList<T> tlist = new ArrayList<>();
        //链接数据库
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/schooltest2?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
                "root",
                "123456");
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);//获取结果集

        ResultSetMetaData metaData = resultSet.getMetaData();//获取元数据--元数据中包含数据库的表中所有信息
        System.out.println("根据结果获取了结果集中的所有元数据为" + metaData);

        int count = metaData.getColumnCount();//从元数据中获取了表的列数
        System.out.println("从元数据中获取了表的列数" + count);
        while (resultSet.next()){//结果集的下一行
            T t = byteClss.newInstance();//实例化类对象

            for (int i = 1; i < count+1; i++) {
                Object value = resultSet.getObject(i);
                if (value != null){
                    String columnName = metaData.getColumnName(i);//获取每i行的列名
//                    System.out.println("columnName = " + columnName);
                    Field field = byteClss.getDeclaredField(columnName);

                    field.setAccessible(true);
                    field.set(t,value);
                }

//                System.out.println("tlist = " + tlist);
            }tlist.add(t);

        }
//        System.out.println("tlist = " + tlist);




        return tlist;
        }

}
